package com.youdoneed.community.forum.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.youdoneed.community.forum.dao.*;
import com.youdoneed.community.forum.entity.*;
import com.youdoneed.community.forum.vo.*;
import com.youdoneed.community.group.dao.ForumuserinforumgroupMapper;
import com.youdoneed.community.group.entity.Forumuserinforumgroup;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.friends.vo.UserRelationsVO;
import com.youdoneed.user.vo.ContactUser;
import com.youdoneed.user.vo.UserShow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.TimeUtils;
import com.youdoneed.community.common.utils.MessageComparator;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.common.vo.PageData;
import com.youdoneed.community.group.dao.ForumgroupMapper;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.media.dao.ForummediaresourceMapper;
import com.youdoneed.community.media.entity.Forummediaresource;
import com.youdoneed.community.media.service.ForummediaresourceService;
import com.youdoneed.news.feign.NewsClient;
import com.youdoneed.news.model.CmfPostsDtlVo;
import com.youdoneed.news.model.CmfPostsListVo;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;

@Service
public class ForummessageService {

    private final Logger logger = LoggerFactory.getLogger(ForumcommentService.class);

    @Autowired
    ForummessageMapper forummessageMapper;

    @Autowired
    ForummessagelabelService forummessagelabelService;

    @Autowired
    ForumlikespointrecordService forumlikespointrecordService;

    @Autowired
    ForumcommentService forumcommentService;

    @Autowired
    ForumcommentMapper forumcommentMapper;

    @Autowired
    ForumgroupMapper forumgroupMapper;

    @Autowired
    ForummediaresourceMapper forummediaresourceMapper;

    @Autowired
    NewsClient newsClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    ForummsglabelrelService forummsglabelrelService;

    @Autowired
    ForummediaresourceService forummediaresourceService;

    @Autowired
    ForummessagelabelMapper forummessagelabelMapper;

    @Autowired
    ForumlikespointrecordMapper forumlikespointrecordMapper;

    @Autowired
    ForumallowviewrecordService forumallowviewrecordService;

    @Autowired
    ForummessageshieldrecordService forummessageshieldrecordService;

    @Autowired
    ForummsglabelrelMapper forummsglabelrelMapper;

    @Autowired
    ForumuserinforumgroupMapper forumuserinforumgroupMapper;

    @Autowired
    ForumallowviewrecordMapper forumallowviewrecordMapper;

    @Autowired
    ForumuserattentionanotherrelService forumuserattentionanotherrelService;

    @Autowired
    ForumnoticeMapper forumnoticeMapper;

    @Autowired
    FriendsClient friendsClient;

    @Autowired
    MsgViewRecordService msgViewRecordService;

    /**
     * 分享次数+1
     *
     * @param msgId
     * @author lid
     * @date 2017.10.31
     */
    public void addShareCount(String msgId) {
        if (!StringUtils.hasText(msgId)) {
            throw new AppException("msgId为空!");
        }

        try {
            forummessageMapper.addShareCount(msgId);
        } catch (Exception e) {
            logger.info("增加分享次数失败!" + e.getMessage());
        }
    }

    /**
     * 当用户修改头像或者昵称时，把所有的帖子、评论、点赞数据都更改为最新的数据
     *
     * @param userId
     * @param nickName
     * @param userHeadUrl
     * @return int
     * @author lid
     * @date 2017.8.11
     */
    public void updateUserInfo(String userId, String nickName, String userHeadUrl) {
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }
        try {
            updateUserInfoVo vo = new updateUserInfoVo();
            vo.setNickName(nickName);
            vo.setUserHeadUrl(userHeadUrl);
            vo.setUserId(userId);
            logger.info("修改帖子、评论、点赞中的用户信息！");
            forummessageMapper.updateUserInfo(vo);
            forumcommentMapper.updateUserInfo(vo);
            forumlikespointrecordMapper.updateUserInfo(vo);
            forumnoticeMapper.updateUserInfo(vo);
            logger.info("修改用户信息成功");

        } catch (Exception e) {
            logger.info("保存猿圈信息失败" + e);
        }

    }


    /**
     * 获取我的帖子
     *
     * @param userId
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.7
     */
    public List<Forummessage> getMyForummessages(String userId, Date beforeDeadTime, Date lastDeadtime) {
        /**
         * 不能获取我的点赞帖
         */
        long startTime = System.currentTimeMillis();   //获取开始时间
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (null != lastDeadtime) {
            logger.info("null != lastDeadtime");

            List<Forummessage> listMyForummessages = forummessageMapper.getMyMsgsAfterDeadtime(userId, lastDeadtime, new Date());
            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取用户自己的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listMyForummessages;
        }

        if (null != beforeDeadTime) {
            logger.info("null != beforeDeadTime");

            List<Forummessage> listMyForummessages = forummessageMapper.getMyMsgsBeforeDeadtime(userId, beforeDeadTime);
            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取用户自己的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listMyForummessages;
        }

        beforeDeadTime = new Date();
        logger.info("null == lastDeadtime && null == beforeDeadTime");
        List<Forummessage> listMyForummessages = forummessageMapper.getMyMsgsBeforeDeadtime(userId, beforeDeadTime);

        long endTime = System.currentTimeMillis(); //获取结束时间

        logger.info("获取用户自己的帖子成功！耗时：" + (endTime - startTime) + "ms");
        return listMyForummessages;
    }

    /**
     * 获取我关注的用户的帖子
     *
     * @param userId
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.7
     */
    public List<Forummessage> getAttentionForummessages(String userId, Date beforeDeadTime, Date lastDeadtime) {
        long startTime = System.currentTimeMillis();   //获取开始时间
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (null != lastDeadtime) {
            logger.info("null != lastDeadtime");

            List<Forummessage> listAttentionUserMsgs = forummessageMapper.
                    getAttentionUserMsgsAfterDeadtime(userId, lastDeadtime, new Date());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取被关注用户的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listAttentionUserMsgs;
        }

        if (null != beforeDeadTime) {
            logger.info("null != beforeDeadTime");

            List<Forummessage> listAttentionUserMsgs = forummessageMapper.
                    getAttentionUserMsgsBeforeDeadtime(userId, beforeDeadTime);

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取被关注用户的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listAttentionUserMsgs;
        }

        beforeDeadTime = new Date();

        List<Forummessage> listAttentionUserMsgs = forummessageMapper.
                getAttentionUserMsgsBeforeDeadtime(userId, beforeDeadTime);

        long endTime = System.currentTimeMillis(); //获取结束时间
        logger.info("获取被关注用户的帖子成功！耗时：" + (endTime - startTime) + "ms");

        return listAttentionUserMsgs;
    }

    /**
     * 获取好友的帖子
     *
     * @param userId
     * @param beforeDeadTime
     * @param lastDeadtime
     * @return
     */
    public List<Forummessage> getFriendsMsgs(String userId, Date beforeDeadTime, Date lastDeadtime) {

        long startTime = System.currentTimeMillis();   //获取开始时间
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (null != lastDeadtime) {
            logger.info("null != lastDeadtime");

            List<Forummessage> listFriendsMsgs = forummessageMapper.
                    getFriendsMsgsAfterDeadtime(userId, lastDeadtime);

            logger.info("listFriendsMsgs.size():" + listFriendsMsgs.size());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取我的好友的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listFriendsMsgs;
        }

        if (null != beforeDeadTime) {
            logger.info("null != beforeDeadTime");

            List<Forummessage> listFriendsMsgs = forummessageMapper.
                    getFriendsMsgsBeforeDeadtime(userId, beforeDeadTime);

            logger.info("listFriendsMsgs.size():" + listFriendsMsgs.size());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取我的好友的帖子成功！耗时：" + (endTime - startTime) + "ms");

            return listFriendsMsgs;
        }

        beforeDeadTime = new Date();

        List<Forummessage> listFriendsMsgs = forummessageMapper.
                getFriendsMsgsBeforeDeadtime(userId, beforeDeadTime);

        logger.info("listFriendsMsgs.size():" + listFriendsMsgs.size());

        long endTime = System.currentTimeMillis(); //获取结束时间
        logger.info("获取我的好友的帖子成功！耗时：" + (endTime - startTime) + "ms");

        return listFriendsMsgs;
    }

    /**
     * 根据标签获取附近的帖子（新处理方案）
     *
     * @param vo
     * @param userId
     * @author lid
     * @date 2017.10.18
     */
    public List<Forummessage> getNearByMsgs(GetNearByMessagesVo vo, String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId为空!");
        }

        if ((!StringUtils.hasText(userId))
                || (null == vo)
                || (null == vo.getDistance())
                || (null == vo.getUserLatitude())
                || (null == vo.getUserLongitude())) {
            throw new AppException("参数为空!");
        }

        try {

            //获取附近的人的用户id
            List<String> listNearByUserIds = new ArrayList<String>();
            List<UserShow> listNearByUsers = userFeignClient.nearbyUsers(0, 50, vo.getUserLongitude(),
                    vo.getUserLatitude(), vo.getDistance(), false).getData();

            if ((null == listNearByUsers)
                    || (0 == listNearByUsers.size())) {
                return new ArrayList<Forummessage>();
            }

            //找到我的黑名单用户
            List<String> blackList = friendsClient
                    .findFriendIds(2).getData().getBlackIds();

            //获取我的屏蔽用户列表并和黑名单用户合并为不可见用户
            List<String> listShieldUserId = forummessageshieldrecordService.getMyShieldUserRecords(userId);
            listShieldUserId.addAll(blackList);

            for (UserShow userShow : listNearByUsers) {
                if (!listShieldUserId.contains(userShow)) {
                    listNearByUserIds.add(userShow.getUserId());
                }
            }
            logger.info("listNearByUserIds.size():" + listNearByUserIds.size());

            //获取我屏蔽的帖子
            List<String> listShieldMsgs = forummessageshieldrecordService.getMyShieldMsgRecords(userId);

            List<Forummessage> listNearByMsgs = new ArrayList<Forummessage>();
            listNearByMsgs = forummessageMapper.getNearByUserMsgs(vo.getListLabelIds(), listNearByUserIds,
                    listShieldMsgs, vo.getBeforeDeadTime(), vo.getLastDeadTime(), new Date());

            //判断我是否点赞
            List<String> listLikePointRecords = forumlikespointrecordService.getLikePointMsgsByUserId(userId);
            logger.info("listLikePointRecords.size():" + listLikePointRecords.size());

            for (Forummessage msg : listNearByMsgs) {
                if (StringUtils.hasText(msg.getMsgSourceType())) {
                    this.getSourceContent(msg, userId);
                }

                if (StringUtils.hasText(msg.getMsgType())) {
                    this.getShareContent(msg, userId);
                }

                if (listLikePointRecords.contains(msg.getForumMsgId())) {
                    msg.setHasPraised(1);
                }

                if ((null != msg.getShareForummessage())
                        && (listLikePointRecords.contains(msg.getShareForummessage().getForumMsgId()))) {
                    msg.getShareForummessage().setHasPraised(1);
                }

            }
            return listNearByMsgs;
        } catch (Exception e) {
            logger.info("获取附近帖子失败" + e);
            return null;
        }
    }

    /**
     * 根据标签获取附近的帖子
     *
     * @param userLongitud
     * @param lastDeadTime
     * @param distance
     * @author lid
     * @date 2017.7.15
     */
    public List<Forummessage> getNearByUserMsgsByLabel
    (String userId, Double distance, Double userLongitud, Double uerLatitude,
     Date beforeDeadTime, Date lastDeadTime,
     List<String> listLabelIds, Integer hasLabels) {

        long startTime = System.currentTimeMillis();   //获取开始时间
        logger.info("getNearByMessages!distance:" + distance + ",userLongitud:" + userLongitud
                + ",uerLatitude:" + uerLatitude);

        // 1纬度为111133.33333333米 1经度为cos(纬度*PI/180)*111133.33333333米（PI/180=0.017453292519943295）
        // 反之1米等于0.000008998200359928014纬度 1米等于0.000008998200359928014/cos(纬度*0.017453292519943295)的经度

        double ratio = Math.cos(uerLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;

        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude = userLongitud - longitudeDistance;
        Double maxLongitude = userLongitud + longitudeDistance;
        Double minLatitude = uerLatitude - latitudeDistance;
        Double maxLatitude = uerLatitude + latitudeDistance;

        logger.info("ratio:" + ratio + ",longitudeDistance:" + longitudeDistance + ",minLongitude:" + minLongitude + ",maxLongitude:" + maxLongitude +
                ",minLatitude:" + minLatitude + ",maxLatitude:" + maxLatitude);

        if (null == beforeDeadTime) {
            beforeDeadTime = new Date();
        }

        /**
         * afterDeadTime不为空，获取截止时间以后的附近帖
         */
        if (null != lastDeadTime) {

            logger.info("lastDeadTime is not null!");
            /**
             * 找非标签贴
             */
            if (null != hasLabels) {
                logger.info("找非标签贴");
                List<Forummessage> listNearByMsgs = forummessageMapper.
                        getNearByUserMsgsWithOutLabelsAfterDeadtime(minLongitude, maxLongitude,
                                minLatitude, maxLatitude, lastDeadTime);
                logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
                for (Forummessage forummessage : listNearByMsgs) {

                    if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                        this.getSourceContent(forummessage, userId);
                    }

                    if (StringUtils.hasText(forummessage.getMsgType())) {
                        this.getShareContent(forummessage, userId);
                    }

                    int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, forummessage.getForumMsgId());
                    if (0 < myLikesCount) {
                        forummessage.setHasPraised(1);
                    }
                }
                return listNearByMsgs;
            }

            if ((null == listLabelIds)
                    || (0 == listLabelIds.size())) {
                logger.info("null != beforeDeadTime");
                List<Forummessage> listNearByMsgs = forummessageMapper.
                        getNearByUserMsgsAfterDeadtime(minLongitude,
                                maxLongitude, minLatitude, maxLatitude, lastDeadTime, new Date());

                logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");

                for (Forummessage forummessage : listNearByMsgs) {

                    if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                        this.getSourceContent(forummessage, userId);
                    }

                    if (StringUtils.hasText(forummessage.getMsgType())) {
                        this.getShareContent(forummessage, userId);
                    }

                    int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, forummessage.getForumMsgId());
                    if (0 < myLikesCount) {
                        forummessage.setHasPraised(1);
                    }
                }

                return listNearByMsgs;
            }

            List<Forummessage> listNearByMsgs = new ArrayList<Forummessage>();
            for (String labelId : listLabelIds) {
                List<Forummessage> list = forummessageMapper.getNearByUserMsgsAfterDeadtimeByLabel
                        (minLongitude, maxLongitude,
                                minLatitude, maxLatitude, lastDeadTime, labelId);

                if ((null != list)
                        && (0 < list.size())) {
                    listNearByMsgs.addAll(list);
                }
            }
            logger.info("listNearByMsgs.size:" + listNearByMsgs.size());
            return listNearByMsgs;

        }

        /**
         * 找非标签贴
         */
        if (null != hasLabels) {
            logger.info("找非标签贴");
            List<Forummessage> listNearByMsgs = forummessageMapper.
                    getNearByUserMsgsWithOutLabelsBeforeDeadtime(minLongitude, maxLongitude,
                            minLatitude, maxLatitude, beforeDeadTime);
            logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

            for (Forummessage forummessage : listNearByMsgs) {

                if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                    this.getSourceContent(forummessage, userId);
                }

                if (StringUtils.hasText(forummessage.getMsgType())) {
                    this.getShareContent(forummessage, userId);
                }

                int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, forummessage.getForumMsgId());
                if (0 < myLikesCount) {
                    forummessage.setHasPraised(1);
                }
            }

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
            return listNearByMsgs;
        }

        if ((null == listLabelIds)
                || (0 == listLabelIds.size())) {
            logger.info("null != beforeDeadTime");
            List<Forummessage> listNearByMsgs = forummessageMapper.
                    getNearByUserMsgsBeforeDeadtime(minLongitude, maxLongitude,
                            minLatitude, maxLatitude, beforeDeadTime);
            logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

            for (Forummessage forummessage : listNearByMsgs) {

                if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                    this.getSourceContent(forummessage, userId);
                }

                if (StringUtils.hasText(forummessage.getMsgType())) {
                    this.getShareContent(forummessage, userId);
                }

                int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, forummessage.getForumMsgId());
                if (0 < myLikesCount) {
                    forummessage.setHasPraised(1);
                }
            }

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
            return listNearByMsgs;
        }

        List<Forummessage> listNearByMsgs = new ArrayList<Forummessage>();
        for (String labelId : listLabelIds) {
            List<Forummessage> list = forummessageMapper.getNearByUserMsgsBeforeDeadtimeByLabel
                    (minLongitude, maxLongitude,
                            minLatitude, maxLatitude, beforeDeadTime, labelId);

            if ((null != list)
                    && (0 < list.size())) {
                listNearByMsgs.addAll(list);
            }
        }
        logger.info("listNearByMsgs.size:" + listNearByMsgs.size());

        for (Forummessage forummessage : listNearByMsgs) {

            if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                this.getSourceContent(forummessage, userId);
            }

            if (StringUtils.hasText(forummessage.getMsgType())) {
                this.getShareContent(forummessage, userId);
            }

            int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, forummessage.getForumMsgId());
            if (0 < myLikesCount) {
                forummessage.setHasPraised(1);
            }
        }
        return listNearByMsgs;
    }

    /**
     * 获取附近的帖子
     *
     * @param userLongitud
     * @param lastDeadTime
     * @param distance
     * @author lid
     * @date 2017.7.7
     */
    public List<Forummessage> getNearByMessages(Double distance, Double userLongitud, Double uerLatitude,
                                                Date beforeDeadTime, Date lastDeadtime) {
        long startTime = System.currentTimeMillis();   //获取开始时间
        logger.info("getNearByMessages!distance:" + distance + ",userLongitud:" + userLongitud
                + ",uerLatitude:" + uerLatitude);

        // 1纬度为111133.33333333米 1经度为cos(纬度*PI/180)*111133.33333333米（PI/180=0.017453292519943295）
        // 反之1米等于0.000008998200359928014纬度 1米等于0.000008998200359928014/cos(纬度*0.017453292519943295)的经度

        double ratio = Math.cos(uerLatitude * 0.017453292519943295);
        double latitudeDistance = distance * 0.000008998200359928014;

        // 以纬度为标准 纬度换算成等效经度距离
        double longitudeDistance = latitudeDistance / ratio;
        Double minLongitude = userLongitud - longitudeDistance;
        Double maxLongitude = userLongitud + longitudeDistance;
        Double minLatitude = uerLatitude - latitudeDistance;
        Double maxLatitude = uerLatitude + latitudeDistance;

        logger.info("ratio:" + ratio + ",longitudeDistance:" + longitudeDistance + ",minLongitude:" + minLongitude + ",maxLongitude:" + maxLongitude +
                ",minLatitude:" + minLatitude + ",maxLatitude:" + maxLatitude);

        if (null != lastDeadtime) {
            logger.info("null != lastDeadtime");
            List<Forummessage> listNearByMsgs = forummessageMapper.
                    getNearByUserMsgsAfterDeadtime(minLongitude,
                            maxLongitude, minLatitude, maxLatitude, lastDeadtime, new Date());

            logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
            return listNearByMsgs;
        }


        if (null != beforeDeadTime) {
            logger.info("null != beforeDeadTime");
            List<Forummessage> listNearByMsgs = forummessageMapper.
                    getNearByUserMsgsBeforeDeadtime(minLongitude, maxLongitude,
                            minLatitude, maxLatitude, beforeDeadTime);
            logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
            return listNearByMsgs;
        }

        beforeDeadTime = new Date();
        List<Forummessage> listNearByMsgs = forummessageMapper.
                getNearByUserMsgsBeforeDeadtime(minLongitude, maxLongitude,
                        minLatitude, maxLatitude, beforeDeadTime);
        logger.info("listNearByMsgs.size():" + listNearByMsgs.size());

        long endTime = System.currentTimeMillis(); //获取结束时间
        logger.info("获取附近的帖子成功！耗时：" + (endTime - startTime) + "ms");
        return listNearByMsgs;
    }

    /**
     * 获取群组的帖子
     *
     * @param userId
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.7
     */
    public List<Forummessage> getGroupMessages(String userId, Date beforeDeadTime, Date lastDeadtime) {
        long startTime = System.currentTimeMillis();   //获取开始时间

        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空！");
        }

        if (null != lastDeadtime) {
            logger.info("null != lastDeadtime");
            List<Forummessage> listGroupMsgs = forummessageMapper.
                    getGroupMsgsAfterDeadtime(userId, lastDeadtime, new Date());

            long endTime = System.currentTimeMillis(); //获取结束时间
            logger.info("获取群组的帖子成功！耗时：" + (endTime - startTime) + "ms");
            return listGroupMsgs;
        }

        if (null != beforeDeadTime) {
            logger.info("null != beforeDeadTime");
            List<Forummessage> listGroupMsgs = forummessageMapper.
                    getGroupMsgsBeforeDeadtime(userId, beforeDeadTime);

            logger.info("listGroupMsgs.size()：" + listGroupMsgs.size());

            long endTime = System.currentTimeMillis(); //获取结束时间
            return listGroupMsgs;
        }

        beforeDeadTime = new Date();

        List<Forummessage> listGroupMsgs = forummessageMapper.
                getGroupMsgsBeforeDeadtime(userId, beforeDeadTime);

        logger.info("listGroupMsgs.size()：" + listGroupMsgs.size());

        long endTime = System.currentTimeMillis(); //获取结束时间
        logger.info("获取群组的帖子成功！耗时：" + (endTime - startTime) + "ms");
        return listGroupMsgs;
    }

    /**
     * 获取用户关注的新闻内容并赋值到帖子中
     *
     * @param beforeDeadTime
     * @param lastDeadtime
     * @param userId
     * @return
     * @author lid
     * @date 2017.7.24
     */
    public List<Forummessage> getNewsMsgs(Date beforeDeadTime, Date lastDeadtime, String userId) {
        if (!StringUtils.hasText(userId)) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        logger.info("getNewsMsgs!");

        List<CmfPostsListVo> listCmfPostsListVo = new ArrayList<CmfPostsListVo>();
        if (null != lastDeadtime) {
            listCmfPostsListVo = newsClient.getNewsForHomePage(null,
                    Integer.valueOf(String.valueOf(lastDeadtime.getTime() / 1000)), userId).getData();
        } else if (null != beforeDeadTime) {
            listCmfPostsListVo = newsClient.getNewsForHomePage(Integer.valueOf(String.valueOf(beforeDeadTime.getTime() / 1000)),
                    null, userId).getData();
        } else {
            Date now = new Date();
            logger.info("now:" + now);
            listCmfPostsListVo = newsClient.getNewsForHomePage(Integer.valueOf(String.valueOf(now.getTime() / 1000)),
                    null, userId).getData();
        }

        if (null == listCmfPostsListVo) {
            logger.info("null == listCmfPostsListVo");
            return null;
        }else{
            logger.info("listCmfPostsListVo.size():" + listCmfPostsListVo.size());
        }

        List<Forummessage> listNewsMsgs = new ArrayList<Forummessage>();
        for (CmfPostsListVo cmfPostsListVo : listCmfPostsListVo) {
            Forummessage newsMsg = new Forummessage();
            Integer showDate = cmfPostsListVo.getShowDate();
            if (null == showDate) {
                continue;
            }

            Long newShowDate = (long) showDate * 1000;

            Date createDate = TimeUtils.getDateByTimestamp(newShowDate);
            newsMsg.setMsgType(ForumServciceStatic.newsMsg);

            newsMsg.setCreateDate(createDate);
            newsMsg.setCmfPostsListVo(cmfPostsListVo);
            newsMsg.setForumMsgId(cmfPostsListVo.getId().toString());
            listNewsMsgs.add(newsMsg);
        }
        logger.info("listNewsMsgs.size():" + listNewsMsgs.size());
        return listNewsMsgs;
    }

    /**
     * 获取首页帖子的第二种实现形式！
     * 1，分为个人帖和群组贴和新闻内容
     * 2，获取用户本人、关注的用户、附近的用户、手机通讯录已注册未关注的用户的ID集合，然后获取上述用户的帖子
     * 3，获取群组的帖子
     * 4，获取分享的内容
     * 5，
     *
     * @param vo
     * @return List<Forummessage>
     * @date 2017.10.10
     */
    public List<Forummessage> getHomePageMsgs(IndexMsgParamVo vo) {

        logger.info("getHomePageMsgs");
        if (null == vo) {
            logger.info("参数为空！");
            throw new AppException("参数为空！");
        }

        if (!StringUtils.hasText(vo.getUserId())) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }
        long time1 = System.currentTimeMillis();
        //获取我的帖子
        List<Forummessage> listMyMsgs = this.getMyForummessages(vo.getUserId(),
                vo.getBeforeDeadTime(), vo.getLastDeadTime());

        long time2 = System.currentTimeMillis();
        logger.info("获取我的帖子耗时："+(time2 - time1));

        //获取我关注的用户的id
        List<String> listMyAttentionedUserIds = forumuserattentionanotherrelService.getMyAttentionUsers(vo.getUserId());
        long time3 = System.currentTimeMillis();
        logger.info("获取我关注的用户的id耗时："+(time3 - time2));

        //获取附近的人的用户id
        List<String> listNearByUserIds = new ArrayList<String>();

        User presentUser = userFeignClient.getUser(vo.getUserId()).getData();
        if ((null != presentUser)
                && (1 == presentUser.getShowNearbyArticle())) {
            List<UserShow> listNearByUsers = userFeignClient.nearbyUsers(0, 50, vo.getUserLongitud(),
                    vo.getUerLatitude(), vo.getDistance(), false).getData();
            if ((null != listNearByUsers)
                    && (0 < listNearByUsers.size())) {
                for (UserShow userShow : listNearByUsers) {
                    if(!listMyAttentionedUserIds.contains(userShow.getUserId())){
                        listNearByUserIds.add(userShow.getUserId());
                    }
                }
            }
        }
        long time4 = System.currentTimeMillis();
        logger.info("获取附近的人耗时："+(time4 - time3));

        //获取手机通讯录已注册未关注的用户id
        List<String> listPhoneFriendsUserIds = new ArrayList<String>();
        List<ContactUser> listContactUser = userFeignClient.getContactUsers().getData();

        long time5 = System.currentTimeMillis();
        logger.info("获取手机通讯录已注册未关注的用户耗时："+(time5 - time4));


        if ((null != listContactUser)
                && (0 < listContactUser.size())) {
            int size = listContactUser.size();

            for (ContactUser contactUser : listContactUser) {
                if (!listMyAttentionedUserIds.contains(contactUser.getUser().getUserId())) {
                    listPhoneFriendsUserIds.add(contactUser.getUser().getUserId());
                }
            }
        }
        /**
         * 找到我的黑名单用户
         */
        List<String> blackList = friendsClient
                .findFriendIds(2).getData().getBlackIds();

        long time6 = System.currentTimeMillis();
        logger.info("获取的黑名单用户耗时："+(time6 - time5));

        /**
         * 获取我的屏蔽用户列表
         */
        List<String> listShieldUserId = forummessageshieldrecordService.getMyShieldUserRecords(vo.getUserId());
        long time7 = System.currentTimeMillis();
        logger.info("获取我的屏蔽用户列表耗时："+(time7 - time6));

        List<String> listShieldMsgs = forummessageshieldrecordService.getMyShieldMsgRecords(vo.getUserId());
        long time8 = System.currentTimeMillis();
        logger.info("获取我的屏蔽帖子列表耗时："+(time8 - time7));

        //未关注的用户：附近未关注的用户和手机通讯录已注册未关注的用户
        List<String> listNotAttentioneduserIds = new ArrayList<>(listPhoneFriendsUserIds.size());
        for (String userId : listPhoneFriendsUserIds) {
            listNotAttentioneduserIds.add(userId);
        }

        Iterator<String> iterator = listNearByUserIds.iterator();
        while (iterator.hasNext()) {
            String userId = iterator.next();
            if (listNotAttentioneduserIds.contains(userId)) {
                iterator.remove();
            }
        }

        listNotAttentioneduserIds.addAll(listNearByUserIds);
        if ((null != blackList)
                && (0 < blackList.size())) {
            Iterator<String> iterator1 = listMyAttentionedUserIds.iterator();
            while (iterator1.hasNext()) {
                String userId = iterator1.next();
                if (blackList.contains(userId)) {
                    iterator1.remove();
                    continue;
                }

                if (listShieldUserId.contains(userId)) {
                    iterator1.remove();
                    continue;
                }
            }

            Iterator<String> iterator2 = listNotAttentioneduserIds.iterator();
            while (iterator2.hasNext()) {
                String userId = iterator2.next();
                if (blackList.contains(userId)) {
                    iterator2.remove();
                    continue;
                }

                if (listShieldUserId.contains(userId)) {
                    iterator2.remove();
                    continue;
                }
            }
        }
        long time9 = System.currentTimeMillis();
        logger.info("处理未关注的用户耗时："+(time9 - time8));
        /**
         * 找listUserIds中用户发的帖
         * 处理屏蔽（隐藏）的帖子
         */
        if ((null == listNotAttentioneduserIds)
                || (0 == listNotAttentioneduserIds.size())) {
            listNotAttentioneduserIds = null;
        }

        if ((null == listMyAttentionedUserIds)
                || (0 == listMyAttentionedUserIds.size())) {
            listMyAttentionedUserIds = null;
        }

        if ((null == listShieldMsgs)
                || (0 == listShieldMsgs.size())) {
            listShieldMsgs = null;
        }

        List<Forummessage> msgsByUserList = forummessageMapper.getHomePageMsgsByUserList(vo.getUserId(),
                listNotAttentioneduserIds, listMyAttentionedUserIds, listShieldMsgs, vo.getBeforeDeadTime(),
                vo.getLastDeadTime(), new Date());

        long time10 = System.currentTimeMillis();
        logger.info("获取msgsByUserList耗时："+(time10 - time9));

        //获取我的群组里面的帖子
        List<Forummessage> listGroupMsgs = this.getGroupMessages(vo.getUserId(),
                vo.getBeforeDeadTime(), vo.getLastDeadTime());
        long time11 = System.currentTimeMillis();
        logger.info("获取我的群组里面的帖子耗时："+(time11 - time10));

        if ((null != listGroupMsgs)
                && (0 < listGroupMsgs.size())) {
            Iterator<Forummessage> iterator1 = listGroupMsgs.iterator();
            while (iterator1.hasNext()) {
                Forummessage groupMsg = iterator1.next();
                if ((null != listShieldMsgs)
                        && (listShieldMsgs.contains(groupMsg.getForumMsgId()))) {
                    iterator1.remove();
                    continue;
                }

                if ((null != listShieldUserId)
                        && (listShieldUserId.contains(groupMsg.getUserId()))) {
                    iterator1.remove();
                    continue;
                }
            }
        }
        /**
         * 获取用户关注的新闻内容并赋值到帖子中
         */
        List<Forummessage> listNewsMsgs = this.getNewsMsgs(vo.getBeforeDeadTime(), vo.getLastDeadTime(), vo.getUserId());
        long time12 = System.currentTimeMillis();
        logger.info("获取用户关注的新闻内容并赋值到帖子中耗时："+(time12 - time11));


        List<Forummessage> listTotalMsgs = this.jointAllMsgs(vo.getUserId(), listMyMsgs, msgsByUserList, listGroupMsgs, listNewsMsgs);
        long time13 = System.currentTimeMillis();
        logger.info("帖子处理耗时："+(time13 - time12));

        //判断我是否点赞
        List<String> listLikePointRecords = forumlikespointrecordService.getLikePointMsgsByUserId(vo.getUserId());
        long time14 = System.currentTimeMillis();
        logger.info("获取点赞记录耗时："+(time14 - time13));

        if (listTotalMsgs.size() >= ForumServciceStatic.msgMaxNumber) {
            listTotalMsgs = listTotalMsgs.subList(0, ForumServciceStatic.msgMaxNumber);
        }

        for (Forummessage msg : listTotalMsgs) {
            System.out.println(msg.getUserId());

            if (listLikePointRecords.contains(msg.getForumMsgId())) {
                msg.setHasPraised(1);
            }

            if ((null != msg.getShareForummessage())
                    && (listLikePointRecords.contains(msg.getShareForummessage().getForumMsgId()))) {
                msg.getShareForummessage().setHasPraised(1);
            }

            if ((null != listMyAttentionedUserIds)
                    && (0 < listMyAttentionedUserIds.size())
                    && (listMyAttentionedUserIds.contains(msg.getUserId()))) {
                msg.setIsAttentioned(ForumServciceStatic.attentioned);
            }

            /**
             * 判断帖子来源：附近帖还是手机通讯录好友的帖子
             */
            if ((listPhoneFriendsUserIds.contains(msg.getUserId()))
                    && (!StringUtils.hasText(msg.getMsgSourceType()))) {
                msg.setMsgSourceType(ForumServciceStatic.phoneBookFriendMsg);
                for (ContactUser contactUser : listContactUser) {
                    if (msg.getUserId().equals(contactUser.getUser().getUserId())) {
                        msg.setContactName(contactUser.getContactName());
                        break;
                    }
                }
                continue;
            }
            //logger.info("判断是否来自附近帖");
            if (listNearByUserIds.contains(msg.getUserId())) {
                msg.setMsgSourceType(ForumServciceStatic.nearByMsg);
            }
        }
        long time15 = System.currentTimeMillis();
        logger.info("最后步骤耗时："+(time15 - time14));
        return listTotalMsgs;
    }

    /**
     * 将用户id合并到一个List中
     *
     * @param listElement
     * @return
     */
    public List<String> jointAllUserIds(List<String>... listElement) {
        List<String> listResult = new ArrayList<String>();
        for (List<String> list : listElement) {
            if ((null == list)
                    || (0 == list.size())) {
                continue;
            }

            for (String userId : list) {
                if (!listResult.contains(userId)) {
                    listResult.add(userId);
                }
            }
        }
        logger.info("listResult.size():" + listResult.size());
        return listResult;
    }


    /**
     * 首页帖子内容，包括如下情况
     * 1，自己的帖子
     * 2，关注的用户
     * 3，附近的帖子
     * 4，群组的帖子
     * 5，手机通讯录用户的帖子（）
     * 6，直播，直播回放（暂不处理）
     * 7，音乐
     * 8，分享链接
     * 9，好友赞了别人（如果帖不是公开帖， 点赞就不能生成新帖）（也是属于好友的帖子里面）
     *
     * @param vo
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.7
     */
    @SuppressWarnings("unchecked")
    public List<Forummessage> getIndexForummessages(IndexMsgParamVo vo) {
        logger.info("getIndexForummessages");
        if (null == vo) {
            logger.info("参数为空！");
            throw new AppException("参数为空！");
        }

        if (!StringUtils.hasText(vo.getUserId())) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (null == vo.getBeforeDeadTime()) {
            Date beforeDeadTime = new Date();
            logger.info("beforeDeadTime is null! new beforeDeadTime:" + new SimpleDateFormat("yy/MM/dd HH:mm").format(beforeDeadTime));
            vo.setBeforeDeadTime(beforeDeadTime);
        }

        //获取我的帖子
        List<Forummessage> listMyMsgs = this.getMyForummessages(vo.getUserId(),
                vo.getBeforeDeadTime(), vo.getLastDeadTime());

		/*for(Forummessage forummessage:listMyMsgs){
            if(forummessage.getForumMsgId().equals("38abd11ea1ab494e9e76de7237e1ab9f")){
				logger.info("从我的帖子中获取");
				break;
			}
		}*/
        //获取关注用户的帖子
        List<Forummessage> listAttentionUserMsgs = this.getAttentionForummessages(vo.getUserId(),
                vo.getBeforeDeadTime(), vo.getLastDeadTime());
        if (null != listAttentionUserMsgs
                && 0 < listAttentionUserMsgs.size()) {
            for (Forummessage forummessage : listAttentionUserMsgs) {
                forummessage.setIsAttentioned(ForumServciceStatic.attentioned);
            }
        }

		/*for(Forummessage forummessage:listAttentionUserMsgs){
            if(forummessage.getForumMsgId().equals("38abd11ea1ab494e9e76de7237e1ab9f")){
				logger.info("从关注用户中获取");
				break;
			}
		}*/

        //获取朋友的帖子
        /**
         * 好友默认关注，因此只需获取关注用户的帖子即可
         * @date 2017.8.3
         */
        /*List<Forummessage> listFriendsMsgs = this.getFriendsMsgs(vo.getUserId(),
				vo.getBeforeDeadTime(), vo.getLastDeadTime());*/

        //获取附近的帖子
        //判断用户是否开启显示附近的帖子
        List<Forummessage> listNearByMsgs = new ArrayList<Forummessage>();

        User user = userFeignClient.getUser(vo.getUserId()).getData();
        if ((null != user)
                && (1 == user.getShowNearbyArticle())) {
            listNearByMsgs = this.getNearByMessages(
                    Double.valueOf(vo.getDistance()), vo.getUserLongitud(),
                    vo.getUerLatitude(), vo.getBeforeDeadTime(), vo.getLastDeadTime());
        }

        /**
         * 设置为附近帖,删除黑名单用户的帖子
         */

        List<String> blackList = friendsClient
                .findFriendIds(2).getData().getBlackIds();

        if ((null != listNearByMsgs)
                && (0 < listNearByMsgs.size())) {
            if (null == blackList
                    || 0 == blackList.size()) {
                //如果黑名单为空，则直接将附近的帖赋值
                logger.info("黑名单为空");
                for (Forummessage forummessage : listNearByMsgs) {
                    forummessage.setMsgSourceType(ForumServciceStatic.nearByMsg);
                }
            } else {
                //如果黑名单不为空，则将附近的处于黑名单中的帖删除，其余的赋值
                Iterator<Forummessage> iterator = listNearByMsgs.iterator();
                while (iterator.hasNext()) {
                    Forummessage forummessage = iterator.next();
                    if (blackList.contains(forummessage.getUserId())) {
                        iterator.remove();
                        continue;
                    }

                    forummessage.setMsgSourceType(ForumServciceStatic.nearByMsg);
                }
            }
        }

		/*for(Forummessage forummessage:listNearByMsgs){
			if(forummessage.getForumMsgId().equals("38abd11ea1ab494e9e76de7237e1ab9f")){
				logger.info("从附近帖子中获取");
				break;
			}
		}*/

        //获取我的群组里面的帖子
        List<Forummessage> listGroupMsgs = this.getGroupMessages(vo.getUserId(),
                vo.getBeforeDeadTime(), vo.getLastDeadTime());


		/*for(Forummessage forummessage:listGroupMsgs){
			if(forummessage.getForumMsgId().equals("38abd11ea1ab494e9e76de7237e1ab9f")){
				logger.info("从我的群组中获取");
				break;
			}
		}*/

        /**
         * 获取用户关注的新闻内容并赋值到帖子中
         */
        List<Forummessage> listNewsMsgs = this.getNewsMsgs(vo.getBeforeDeadTime(), vo.getLastDeadTime(), vo.getUserId());


        List<Forummessage> listTotalMsgs = this.jointAllMsgs(vo.getUserId(), listMyMsgs, listAttentionUserMsgs, listNearByMsgs, listGroupMsgs, listNewsMsgs);
        logger.info("listTotalMsgs.size():" + listTotalMsgs.size());

        //判断当前用户是否对当前帖子屏蔽、如果屏蔽则删除，否则记录帖子的点赞情况
        if ((null != listTotalMsgs)
                && (0 < listTotalMsgs.size())) {

            List<Forummessageshieldrecord> myShieldRecord = forummessageshieldrecordService.getMyShieldRecords(vo.getUserId());
            for (int index = 0; index < listTotalMsgs.size(); index++) {
                //判断当前帖子是否被屏蔽
                if (this.hasSheild(myShieldRecord, listTotalMsgs.get(index))) {
                    logger.info("当前帖子被屏蔽！" + listTotalMsgs.get(index).getForumMsgId());
                    listTotalMsgs.remove(index);
                    index--;
                    continue;
                }

                Forummessage indexMsg = listTotalMsgs.get(index);
                int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(vo.getUserId(), indexMsg.getForumMsgId());
                if (0 < myLikesCount) {
                    indexMsg.setHasPraised(1);
                }

                /**
                 * 判断分享的帖子我是否点赞
                 */
                if (null != indexMsg.getShareForummessage()) {
                    int shareMsgLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(vo.getUserId(),
                            indexMsg.getShareForummessage().getForumMsgId());
                    if (0 < shareMsgLikesCount) {
                        indexMsg.getShareForummessage().setHasPraised(1);
                    }
                }
            }
        }

        logger.info("listTotalMsgs.size():" + listTotalMsgs.size());
        if (ForumServciceStatic.msgMaxNumber >= listTotalMsgs.size()) {
            return listTotalMsgs;
        }

        return listTotalMsgs.subList(0, ForumServciceStatic.msgMaxNumber);
    }

    /**
     * 判断我是否屏蔽了当前帖子
     *
     * @param forummessage
     * @return
     */
    public boolean hasSheild(List<Forummessageshieldrecord> listShielRecord, Forummessage forummessage) {
        if ((null == listShielRecord)
                || (0 == listShielRecord.size())) {
            return false;
        }

        for (int index = 0; index < listShielRecord.size(); index++) {
            Forummessageshieldrecord record = listShielRecord.get(index);
            if ((StringUtils.hasText(record.getForumMsgId()))
                    && (record.getForumMsgId().equals(forummessage.getForumMsgId()))) {
                return true;
            }

            if ((StringUtils.hasText(record.getShieldedUserId()))
                    && (record.getShieldedUserId().equals(forummessage.getUserId()))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 整合所有的帖子
     *
     * @param listElement
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.11
     */
    @SuppressWarnings("unchecked")
    public List<Forummessage> jointAllMsgs(String userId, List<Forummessage>... listElement) {
        List<Forummessage> listTotalMsgs = new ArrayList<Forummessage>();
        for (List<Forummessage> list : listElement) {
            if ((null != list)
                    && (0 < list.size())) {
                //logger.info("list.size():"+list.size());
                listTotalMsgs.addAll(list);
            }
        }
        logger.info("listTotalMsgs.size()：" + listTotalMsgs.size());

        //对帖子进行时间排序并去重
        long startTime = System.currentTimeMillis();   //获取开始时间
        List<Forummessage> list = this.sortAllMsgs(userId, listTotalMsgs);
        long endTime = System.currentTimeMillis();   //获取开始时间
        logger.info("对帖子进行时间排序并去重成功！耗时：" + (endTime - startTime) + "ms");

        return list;
    }

    /**
     * 对帖子列表进行排序并去重
     *
     * @param listMsgs
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.11
     */
    public List<Forummessage> sortAllMsgs(String userId, List<Forummessage> listMsgs) {
        logger.info("sortAllMsgs!size:" + listMsgs.size());

        /**
         * 去重
         */
        List<String> listMsgId = new ArrayList<String>();
        List<String> listLikePointMsgId = new ArrayList<String>();

        Iterator<Forummessage> iterator = listMsgs.iterator();
        while (iterator.hasNext()) {
            Forummessage forummessage = iterator.next();
            if ((StringUtils.hasText(forummessage.getMsgSourceType()))
                    && (ForumServciceStatic.likePointMsg.equals(forummessage.getMsgSourceType()))) {
                //点赞帖
                if (listLikePointMsgId.contains(forummessage.getSourceId())) {
                    iterator.remove();
                    continue;
                } else {
                    listLikePointMsgId.add(forummessage.getSourceId());
                }
            } else {
                if (listMsgId.contains(forummessage.getForumMsgId())) {
                    iterator.remove();
                    continue;
                } else {
                    listMsgId.add(forummessage.getForumMsgId());
                }
            }
        }
        logger.info("listMsgs.size():" + listMsgs.size());

        Iterator<Forummessage> iterator1 = listMsgs.iterator();
        while (iterator1.hasNext()) {
            Forummessage forummessage = iterator1.next();

            if ((StringUtils.hasText(forummessage.getMsgSourceType()))
                    && (ForumServciceStatic.likePointMsg.equals(forummessage.getMsgSourceType()))) {
                //点赞帖
                if (listMsgId.contains(forummessage.getSourceId())) {
                    iterator1.remove();
                    continue;
                }
            }

            if (StringUtils.hasText(forummessage.getMsgType())) {
                this.getShareContent(forummessage, userId);
            }

            if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                this.getSourceContent(forummessage, userId);
            }
        }
        logger.info("去重结束");
        MessageComparator comparator = new MessageComparator();
        //排序
        Collections.sort(listMsgs, comparator);
        return listMsgs;
    }

    /**
     * 编辑帖子
     * 编辑帖子逻辑：
     * 1，修改content内容
     * 2，修改标签
     * 3，修改媒体资源
     * 4，隐私设置
     *
     * @param editMsgVo
     * @return
     * @author lid
     * @date 2017.7.21
     */
    @Transactional
    public int editForumMessage(EditMsgVo editMsgVo) {
        if (null == editMsgVo) {
            logger.info("参数为空！");
            throw new AppException("参数为空！");
        }

        if (!StringUtils.hasText(editMsgVo.getForumMsgId())) {
            logger.info("msgId参数为空！");
            throw new AppException("msgId参数为空！");
        }

        Forummessage forummessage = forummessageMapper.selectByPrimaryKey(editMsgVo.getForumMsgId());
        if (null == forummessage) {
            logger.info("未找到需要编辑的帖子！");
            throw new AppException("未找到需要编辑的帖子！");
        }

        /**
         * 修改content内容,隐私设置以及标签
         */
        if (StringUtils.hasText(editMsgVo.getMsgContent())) {
            forummessage.setMsgContent(editMsgVo.getMsgContent());
        }

        if (null != editMsgVo.getAllowViewStatus()) {
            forummessage.setAllowViewStatus(editMsgVo.getAllowViewStatus());
        }

        if (null != editMsgVo.getImageLayoutType()) {
            forummessage.setImageLayoutType(editMsgVo.getImageLayoutType());
        } else {
            forummessage.setImageLayoutType(0);
        }

        if (null != editMsgVo.getUserLongitude()) {
            forummessage.setUserLongitude(editMsgVo.getUserLongitude());
        }

        if (null != editMsgVo.getUserLatitude()) {
            forummessage.setUserLatitude(editMsgVo.getUserLatitude());
        }

        if (StringUtils.hasText(editMsgVo.getPostionLabel())) {
            forummessage.setPostionLabel(editMsgVo.getPostionLabel());
        }

        if (StringUtils.hasText(editMsgVo.getNation())) {
            forummessage.setNation(editMsgVo.getNation());
        }

        if (StringUtils.hasText(editMsgVo.getCity())) {
            forummessage.setCity(editMsgVo.getCity());
        }

        if (StringUtils.hasText(editMsgVo.getProvince())) {
            forummessage.setProvince(editMsgVo.getProvince());
        }

        if (StringUtils.hasText(editMsgVo.getDistrict())) {
            forummessage.setDistrict(editMsgVo.getDistrict());
        }

        if ((null != editMsgVo.getListMsgLabelIds()) && (0 < editMsgVo.getListMsgLabelIds().size())
                || (StringUtils.hasText(editMsgVo.getUserDefineLabel()))) {
            //设置为存在标签
            logger.info("修改的帖子存在标签！");
            forummessage.setHasLabels(1);
        }

        if (StringUtils.hasText(editMsgVo.getMsgLanguage())) {
            forummessage.setMsgLanguage(editMsgVo.getMsgLanguage());
        }
        //修改创建时间
        forummessage.setCreateDate(new Date());
        int result = forummessageMapper.updateByPrimaryKey(forummessage);
        logger.info("修改主字段完成！");

        /**
         * 修改标签
         */
        forummsglabelrelMapper.deleteByMsgId(editMsgVo.getForumMsgId());

        //保存用户自定义标签
        if (StringUtils.hasText(editMsgVo.getUserDefineLabel())) {
            //保存标签
            Forummessagelabel label = new Forummessagelabel();
            String labelId = StringUUIdUtil.getUUID();
            Date createDate = new Date();
            label.setLabelDescribe(editMsgVo.getUserDefineLabel());
            label.setUserId(forummessage.getUserId());
            label.setCreateDate(createDate);
            label.setForumMessageLabelId(labelId);
            label.setLabelStatus(0);
            forummessagelabelMapper.insert(label);

            //保存标签与帖子的关系
            Forummsglabelrel rel = new Forummsglabelrel();
            rel.setForumMsgLabelRelId(StringUUIdUtil.getUUID());
            rel.setCreateDate(new Date());
            rel.setForumMsgId(forummessage.getForumMsgId());
            rel.setForumMessageLabelId(labelId);
            forummsglabelrelService.saveForummsglabelrel(rel);
        }

        //保存标签
        if ((null != editMsgVo.getListMsgLabelIds())
                && (0 < editMsgVo.getListMsgLabelIds().size())) {
            logger.info("保存帖子标签！标签个数：" + editMsgVo.getListMsgLabelIds().size());

            for (String forumMessageLabelId : editMsgVo.getListMsgLabelIds()) {
                Forummsglabelrel rel = new Forummsglabelrel();
                rel.setForumMsgLabelRelId(StringUUIdUtil.getUUID());
                rel.setCreateDate(new Date());
                rel.setForumMsgId(forummessage.getForumMsgId());
                rel.setForumMessageLabelId(forumMessageLabelId);
                forummsglabelrelService.saveForummsglabelrel(rel);
            }
        }
        logger.info("修改帖子标签成功！");
        /**
         * 修改媒体资源
         */
        forummediaresourceMapper.deleteByMsgId(editMsgVo.getForumMsgId());

        //保存媒体资源
        if ((null != editMsgVo.getListForummediaresource())
                && (0 < editMsgVo.getListForummediaresource().size())) {
            for (Forummediaresource forummediaresource : editMsgVo.getListForummediaresource()) {
                forummediaresource.setForumMessageId(editMsgVo.getForumMsgId());
                forummediaresourceService.saveForumMediaResource(forummediaresource);
            }
            logger.info("保存媒体资源成功！");
        }
        logger.info("修改媒体资源成功！");

        /**
         * 修改隐私设置
         */
        forumallowviewrecordService.deleteByMsgId(editMsgVo.getForumMsgId());

        //保存隐私设置
        if (ForumServciceStatic.closeToPartFriends == editMsgVo.getAllowViewStatus()) {
            if ((null != editMsgVo.getListUserId())
                    && (0 < editMsgVo.getListUserId().size())) {
                List<String> listUserId = editMsgVo.getListUserId();
                for (String userId : listUserId) {
                    Forumallowviewrecord forumallowviewrecord = new Forumallowviewrecord();
                    forumallowviewrecord.setAllowedStatus(0);
                    forumallowviewrecord.setAllowedUserId(userId);
                    forumallowviewrecord.setForumMsgId(editMsgVo.getForumMsgId());
                    forumallowviewrecord.setUserId(forummessage.getUserId());
                    forumallowviewrecordService.saveForumallowviewrecord(forumallowviewrecord);
                }
            }
        }

        if (ForumServciceStatic.openToPartFriends == editMsgVo.getAllowViewStatus()) {
            if ((null != editMsgVo.getListUserId())
                    && (0 < editMsgVo.getListUserId().size())) {
                List<String> listUserId = editMsgVo.getListUserId();
                for (String userId : listUserId) {
                    Forumallowviewrecord forumallowviewrecord = new Forumallowviewrecord();
                    forumallowviewrecord.setAllowedStatus(1);
                    forumallowviewrecord.setAllowedUserId(userId);
                    forumallowviewrecord.setForumMsgId(editMsgVo.getForumMsgId());
                    forumallowviewrecord.setUserId(forummessage.getUserId());
                    forumallowviewrecordService.saveForumallowviewrecord(forumallowviewrecord);
                }
            }
        }
        logger.info("修改隐私设置成功！");
        return result;
    }


    /**
     * 发表帖子接口
     *
     * @return int
     * @author lid
     * @date 2017.7.6
     */
    @Transactional
    public String publishForumMessage(CreateMsgVo createMsgVo) {
        logger.info("publishForumMessage");

        //判断参数
        if (null == createMsgVo) {
            logger.info("createMsgVo参数为空！");
            throw new AppException("createMsgVo参数为空！");
        }

        if (!StringUtils.hasText(createMsgVo.getUserId())) {
            logger.info("userId参数为空！");
            throw new AppException("userId参数为空！");
        }

        if (!StringUtils.hasText(createMsgVo.getMsgType())) {
            logger.info("msgType参数为空！");
            throw new AppException("msgType参数为空！");
        }

        /**
         * 判断是否所有内容都为空
         * 1,帖子文本内容为空
         * 2，分享的内容为空
         * 3，媒体资源为空
         */

        if ((StringUtils.hasText(createMsgVo.getMsgSourceType())) && (createMsgVo.getMsgSourceType().equals(ForumServciceStatic.groupMsg))) {
            if ((!StringUtils.hasText(createMsgVo.getMsgContent()))
                    && ((null == createMsgVo.getListForummediaresource()) || (0 == createMsgVo.getListForummediaresource().size()))) {
                logger.info("当前帖子为空！");
                throw new AppException("不能发表空帖！");
            }
        } else {
            if ((!StringUtils.hasText(createMsgVo.getMsgContent()))
                    && (!StringUtils.hasText(createMsgVo.getSourceId()))
                    && ((null == createMsgVo.getListForummediaresource()) || (0 == createMsgVo.getListForummediaresource().size()))) {
                logger.info("当前帖子为空！");
                throw new AppException("不能发表空帖！");
            }
        }


        /**
         * 判断文本内容长度
         */
        if (StringUtils.hasText(createMsgVo.getMsgContent())) {
            if (ForumServciceStatic.maxContentLength < createMsgVo.getMsgContent().length()) {
                logger.info("文本内容超过200个字符！");
                throw new AppException("文字内容超过200个字符！");
            }
        }

        /**
         * 经纬度精度设置
         */
        if (null != createMsgVo.getUserLatitude()) {
            BigDecimal bd = new BigDecimal(createMsgVo.getUserLatitude());
            bd = bd.setScale(6, BigDecimal.ROUND_HALF_UP);
            createMsgVo.setUserLatitude(bd.doubleValue());
        }

        if (null != createMsgVo.getUserLongitude()) {
            BigDecimal bd = new BigDecimal(createMsgVo.getUserLongitude());
            bd = bd.setScale(6, BigDecimal.ROUND_HALF_UP);
            createMsgVo.setUserLongitude(bd.doubleValue());
        }

        /**
         * 只能分享公开的帖子，分享次数+1
         */
        if (ForumServciceStatic.shareMsg.equals(createMsgVo.getMsgType())) {
            logger.info("当前贴为分享贴！增加分享次数");
            if (!StringUtils.hasText(createMsgVo.getSourceId())) {
                logger.info("sourceId为空！");
                throw new AppException("sourceId为空！");
            }
            Forummessage shareForummessage = forummessageMapper.selectByPrimaryKey(createMsgVo.getSourceId());

            if (null == shareForummessage) {
                logger.info("被分享的帖子为空！");
                throw new AppException("被分享的帖子为空！");
            }

            logger.info("AllowViewStatus:" + shareForummessage.getAllowViewStatus());
            logger.info("msgId:" + shareForummessage.getForumMsgId());
            logger.info("content:" + shareForummessage.getMsgContent());

            if (ForumServciceStatic.openToAll != shareForummessage.getAllowViewStatus()) {
                logger.info("只能分享公开贴！");
                throw new AppException("只能分享公开贴！");
            }

            forummessageMapper.addShareCount(createMsgVo.getSourceId());
        }


        //logger.info("new Forummessage");
        String forumMsgId = StringUUIdUtil.getUUID();
        //logger.info("forumMsgId:"+forumMsgId);

        Forummessage forummessage = new Forummessage();
        forummessage.setAllowViewStatus(createMsgVo.getAllowViewStatus());
        forummessage.setCommentCount(0);
        if (null != createMsgVo.getCreateDate()) {
            forummessage.setCreateDate(createMsgVo.getCreateDate());
        } else {
            forummessage.setCreateDate(new Date());
        }
        forummessage.setFirstImageScale(createMsgVo.getFirstImageScale());
        forummessage.setForumMsgId(forumMsgId);
        forummessage.setHeat(0);
        forummessage.setImageLayoutType(createMsgVo.getImageLayoutType());
        forummessage.setLikesCount(0);
        forummessage.setMsgContent(createMsgVo.getMsgContent());
        forummessage.setMsgDelete(0);
        forummessage.setMsgType(createMsgVo.getMsgType());
        forummessage.setMsgSourceType(createMsgVo.getMsgSourceType());
        forummessage.setNickName(createMsgVo.getNickName());
        forummessage.setPostionLabel(createMsgVo.getPostionLabel());
        forummessage.setNation(createMsgVo.getNation());
        forummessage.setProvince(createMsgVo.getProvince());
        forummessage.setCity(createMsgVo.getCity());
        forummessage.setDistrict(createMsgVo.getDistrict());
        forummessage.setProhibit(0);
        forummessage.setReportCount(0);
        forummessage.setUserHeadUrl(createMsgVo.getUserHeadUrl());
        forummessage.setUserId(createMsgVo.getUserId());
        forummessage.setUserLatitude(createMsgVo.getUserLatitude());
        forummessage.setUserLongitude(createMsgVo.getUserLongitude());
        forummessage.setUserType(createMsgVo.getUserType());
        forummessage.setSourceId(createMsgVo.getSourceId());
        forummessage.setMsgLanguage(createMsgVo.getMsgLanguage());
        forummessage.setRecommand(0);

        if ((null == createMsgVo.getListMsgLabelIds() || 0 == createMsgVo.getListMsgLabelIds().size())
                && (!StringUtils.hasText(createMsgVo.getUserDefineLabel()))) {
            logger.info("forummessage.setHasLabels(0)");
            forummessage.setHasLabels(0);
        } else {
            logger.info("forummessage.setHasLabels(1)");
            forummessage.setHasLabels(1);
        }

        logger.info("帖子赋值完成");

        int result = 0;
        try {
            logger.info("保存帖子信息");
            forummessageMapper.insert(forummessage);
        } catch (Exception e) {
            logger.info("保存猿圈信息失败" + e);
            return forumMsgId;
        }

        /**
         * 更新用户的发帖数
         */
        logger.info("用户发帖数+1");
        userFeignClient.totalArticleChange(createMsgVo.getUserId(), 1);

        /**
         * 更新群组发帖数
         */
        if (ForumServciceStatic.groupMsg.equals(createMsgVo.getMsgSourceType())) {
            logger.info("当前帖为群组帖");
            if (!StringUtils.hasText(createMsgVo.getSourceId())) {
                logger.info("群组id为空！");
                throw new AppException("群组id为空！");
            }
            String groupId = createMsgVo.getSourceId();
            logger.info("groupId:" + groupId);
            Forumgroup group = forumgroupMapper.selectByPrimaryKey(groupId);

            Integer groupMsgCount = forummessageMapper.countGroupMsgs(groupId);
            group.setGroupMessageTotal(groupMsgCount);
            forumgroupMapper.updateByPrimaryKey(group);
            logger.info("更新用户发帖数成功！");
        }

        logger.info("保存隐私设置");
        //保存隐私设置
        if (ForumServciceStatic.closeToPartFriends == createMsgVo.getAllowViewStatus()) {
            logger.info("部分好友不可见");
            if ((null != createMsgVo.getListUserId())
                    && (0 < createMsgVo.getListUserId().size())) {
                List<String> listUserId = createMsgVo.getListUserId();

                for (String userId : listUserId) {
                    logger.info("被屏蔽的好友id:" + userId);
                    Forumallowviewrecord forumallowviewrecord = new Forumallowviewrecord();
                    forumallowviewrecord.setAllowedStatus(0);
                    forumallowviewrecord.setAllowedUserId(userId);
                    forumallowviewrecord.setForumMsgId(forumMsgId);
                    forumallowviewrecord.setUserId(createMsgVo.getUserId());
                    forumallowviewrecordService.saveForumallowviewrecord(forumallowviewrecord);
                }
            }
        }

        if (ForumServciceStatic.openToPartFriends == createMsgVo.getAllowViewStatus()) {
            logger.info("部分好友可见");
            if ((null != createMsgVo.getListUserId())
                    && (0 < createMsgVo.getListUserId().size())) {
                List<String> listUserId = createMsgVo.getListUserId();
                for (String userId : listUserId) {
                    logger.info("未屏蔽的好友id:" + userId);
                    Forumallowviewrecord forumallowviewrecord = new Forumallowviewrecord();
                    forumallowviewrecord.setAllowedStatus(1);
                    forumallowviewrecord.setAllowedUserId(userId);
                    forumallowviewrecord.setForumMsgId(forumMsgId);
                    forumallowviewrecord.setUserId(createMsgVo.getUserId());
                    forumallowviewrecordService.saveForumallowviewrecord(forumallowviewrecord);
                }
            }
        }

        //保存用户自定义标签
        if (StringUtils.hasText(createMsgVo.getUserDefineLabel())) {
            //保存标签
            Forummessagelabel label = new Forummessagelabel();
            String labelId = StringUUIdUtil.getUUID();
            Date createDate = new Date();
            label.setLabelDescribe(createMsgVo.getUserDefineLabel());
            label.setUserId(createMsgVo.getUserId());
            label.setCreateDate(createDate);
            label.setForumMessageLabelId(labelId);
            label.setLabelStatus(0);
            forummessagelabelMapper.insert(label);

            //保存标签与帖子的关系
            Forummsglabelrel rel = new Forummsglabelrel();
            rel.setForumMsgLabelRelId(StringUUIdUtil.getUUID());
            rel.setCreateDate(new Date());
            rel.setForumMsgId(forumMsgId);
            rel.setForumMessageLabelId(labelId);
            forummsglabelrelService.saveForummsglabelrel(rel);
        }

        //保存标签
        if ((null != createMsgVo.getListMsgLabelIds())
                && (0 < createMsgVo.getListMsgLabelIds().size())) {
            logger.info("保存帖子标签！标签个数：" + createMsgVo.getListMsgLabelIds().size());

            for (String forumMessageLabelId : createMsgVo.getListMsgLabelIds()) {
                Forummsglabelrel rel = new Forummsglabelrel();
                rel.setForumMsgLabelRelId(StringUUIdUtil.getUUID());
                rel.setCreateDate(new Date());
                rel.setForumMsgId(forumMsgId);
                rel.setForumMessageLabelId(forumMessageLabelId);
                forummsglabelrelService.saveForummsglabelrel(rel);
            }

            logger.info("保存帖子标签成功！");
        }

        //保存媒体资源
        if ((null != createMsgVo.getListForummediaresource())
                && (0 < createMsgVo.getListForummediaresource().size())) {
            for (Forummediaresource forummediaresource : createMsgVo.getListForummediaresource()) {
                forummediaresource.setForumMessageId(forumMsgId);
                forummediaresourceService.saveForumMediaResource(forummediaresource);
            }
            logger.info("保存媒体资源成功！");
        }
        logger.info("发帖成功");
        return forumMsgId;
    }

    @Transactional
    public PageData selectByUserId(String userId, String searchedUserId, Integer rows, Integer currentPage) {
        if ((!StringUtils.hasText(userId))
                || (!StringUtils.hasText(searchedUserId))) {
            throw new AppException("用户id为空");
        }
        try {
            PageData page = new PageData();

            List<Forummessage> list = forummessageMapper.selectByUserId(searchedUserId);
            if (null == list || 0 == list.size()) {
                return null;
            }
            logger.info("list.size():" + list.size());

            if (userId.equals(searchedUserId)) {
                logger.info("当前用户查看自己的个人主页！");

                List<String> listLikePoints = forumlikespointrecordService.getLikePointMsgsByUserId(searchedUserId);

                /**
                 * 查看自己的主页，把自己生成的点赞帖删除
                 */
                Iterator<Forummessage> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Forummessage forummessage = iterator.next();
                    if (null != forummessage.getMsgSourceType()
                            && ForumServciceStatic.likePointMsg.equals(forummessage.getMsgSourceType())
                            && userId.equals(forummessage.getUserId())) {
                        logger.info("当前贴为当前用户的点赞帖，不应在个人主页展示!MsgId:" + forummessage.getForumMsgId());
                        iterator.remove();
                        continue;
                    }

                    if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                        this.getSourceContent(forummessage, userId);
                    }

                    if (StringUtils.hasText(forummessage.getMsgType())) {
                        this.getShareContent(forummessage, userId);
                    }

                    if (listLikePoints.contains(forummessage.getForumMsgId())) {
                        forummessage.setHasPraised(1);
                    }
                }

            } else {
                logger.info("当前用户查看他人的个人主页！");
                List<String> listLikePoints = forumlikespointrecordService.getLikePointMsgsByUserId(userId);


                //找到我的黑名单用户(黑名单是互黑模式)
                UserRelationsVO userRelationsVO = friendsClient
                        .findFriendIds(3).getData();

                List<String> blackList = userRelationsVO.getBlackIds();
                List<String> friendList = userRelationsVO.getFriendIds();
                if (blackList.contains(searchedUserId)) {
                    logger.info("我被拉黑了！");
                    page.setTotal(0);
                    page.setRows(new ArrayList<Forummessage>());
                    return page;
                }

                Iterator<Forummessage> iterator = list.iterator();

                //判断是否仅自己可见
                while (iterator.hasNext()) {
                    Forummessage forummessage = iterator.next();
                    Integer allowViewStatus = forummessage.getAllowViewStatus();
                    logger.info(forummessage.getForumMsgId() + "的allowViewStatus为:" + allowViewStatus);
                    //判断是否仅自己可见
                    if (ForumServciceStatic.openToMySelf == allowViewStatus) {
                        logger.info("当前帖仅自己可见！msgId:" + forummessage.getForumMsgId());
                        iterator.remove();
                        continue;
                    }

                    //判断是否仅好友可见
                    if (ForumServciceStatic.openToFriends == allowViewStatus) {
                        logger.info("仅好友可见");
                        if (!friendList.contains(searchedUserId)) {
                            iterator.remove();
                            continue;
                        }
                    }

                    //判断是否为群组贴
                    if (ForumServciceStatic.openToGroup == allowViewStatus) {
                        logger.info("当前帖为群组贴！");
                        String groupId = forummessage.getSourceId();
                        logger.info("groupId:" + groupId);
                        /**
                         判断userId是否在该群中
                         */
                        Forumuserinforumgroup userInGroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, groupId);
                        if (null == userInGroup) {
                            logger.info("userId不在该群中！不能看到该帖");
                            iterator.remove();
                            continue;
                        }
                    }

                    //判断是否为点赞帖
                    if (ForumServciceStatic.openToPartFriends == allowViewStatus
                            || ForumServciceStatic.closeToPartFriends == allowViewStatus) {

                        Forumallowviewrecord forumallowviewrecord = forumallowviewrecordMapper.
                                selectByUserIdAndMsgId(userId, forummessage.getForumMsgId());

                        if ((ForumServciceStatic.openToPartFriends == allowViewStatus)
                                && (null == forumallowviewrecord)) {
                            logger.info("当前帖仅部分好友可见,并且userId不在可见列表中！");
                            iterator.remove();
                            continue;

                        } else if ((ForumServciceStatic.closeToPartFriends == allowViewStatus)
                                && (null != forumallowviewrecord)) {
                            logger.info("当前帖部分好友不可见,并且userId在不可见列表中！ForumAllowViewRecordId:"
                                    + forumallowviewrecord.getForumAllowViewRecordId());
                            iterator.remove();
                            continue;
                        }

                    }

                    if (StringUtils.hasText(forummessage.getMsgSourceType())) {
                        this.getSourceContent(forummessage, userId);
                    }

                    if (StringUtils.hasText(forummessage.getMsgType())) {
                        this.getShareContent(forummessage, userId);
                    }

                    if (listLikePoints.contains(forummessage.getForumMsgId())) {
                        forummessage.setHasPraised(1);
                    }

                }
            }

            /**
             * 手动分页
             */

            logger.info("list.size():" + list.size());

            Integer length = list.size();
            page.setTotal(length);

            Integer startIndex = rows * (currentPage - 1);
            Integer endIndex = rows * currentPage;
            if (startIndex > length) {
                return null;
            }

            if (endIndex < length) {
                List<Forummessage> listResult = list.subList(startIndex, endIndex);
                page.setRows(listResult);
                return page;
            }
            List<Forummessage> listResult = list.subList(startIndex, length);
            page.setRows(listResult);
            return page;

        } catch (Exception e) {
            logger.error("获取用户帖子异常：" + e);
            return null;
        }
    }

    @Transactional
    public List<Forummessage> selectByGroupId(String userId, String groupId, Integer rows, Integer currentPage) {
        try {
            PageHelper.startPage(currentPage, rows);
            List<Forummessage> list = forummessageMapper.selectByGroupId(groupId);
            if (null == list || 0 == list.size()) {
                return list;
            }

            List<String> forumlikespointrecordList = forumlikespointrecordMapper.getLikePointMsgsByUserId(userId);
            for (Forummessage forummessage : list) {
                if (StringUtils.hasText(forummessage.getMsgType())) {
                    this.getShareContent(forummessage, userId);
                }

                if (forumlikespointrecordList.contains(forummessage.getForumMsgId())) {
                    forummessage.setHasPraised(1);
                }
            }
            return list;
        } catch (Exception e) {
            logger.error("获取群组帖子异常：" + e);
            return null;
        }
    }

    @Transactional
    public int deleteForumMsgById(String forumMsgId) {
        if (!StringUtils.hasText(forumMsgId)) {
            logger.info("forumMsgId");
            throw new AppException("forumMsgId不能为空");
        }
        logger.info("forumMsgId:" + forumMsgId);
        try {
            /**
             * 删除所有点赞生成的帖子
             */
            logger.info("逻辑删除所有点赞生成的帖子");
            //forummessageMapper.deleteLikePointMsgs(forumMsgId);

            /**
             * 用户的发帖数-1
             */
            Forummessage message = forummessageMapper.selectByPrimaryKey(forumMsgId);
            if (null == message) {
                logger.info("待删除的帖子为空");
                throw new AppException("待删除的帖子为空");
            }

            logger.info("用户发帖数-1");
            if (StringUtils.hasText(message.getUserId())) {
                userFeignClient.totalArticleChange(message.getUserId(), -1);
            }

            /**
             * 如果为群组帖子，则将群组发帖数减1
             */
            if (ForumServciceStatic.groupMsg.equals(message.getMsgSourceType())) {
                if (StringUtils.hasText(message.getSourceId())) {
                    Forumgroup group = forumgroupMapper.selectByPrimaryKey(message.getSourceId());
                    if (null != group) {
                        group.setGroupMessageTotal(group.getGroupMessageTotal() - 1);
                        forumgroupMapper.updateByPrimaryKey(group);
                        logger.info("更新群组发帖数成功");
                    }
                }
            }

            return forummessageMapper.updateById(forumMsgId);
        } catch (Exception e) {
            logger.info("删除猿圈帖子失败" + e);
            return 0;
        }
    }

    /**
     * 后台恢复猿圈信息(逻辑恢复)
     *
     * @param
     * @return
     * @author lid
     * @date 2017.8.2
     */
    @Transactional
    public int regainForumMsgById(String forumMsgId) {
        if (!StringUtils.hasText(forumMsgId)) {
            logger.info("forumMsgId");
            throw new AppException("forumMsgId不能为空");
        }
        logger.info("forumMsgId:" + forumMsgId);
        try {
            /**
             * 恢复所有点赞生成的帖子
             */
            logger.info("恢复所有点赞生成的帖子");
            forummessageMapper.regainLikePointMsgs(forumMsgId);

            return forummessageMapper.regainForumMsgById(forumMsgId);
        } catch (Exception e) {
            logger.info("删除猿圈帖子失败" + e);
            return 0;
        }
    }


    @Transactional
    public int deleteForumMsgByUser(String forumMsgId) {
        if (!StringUtils.hasText(forumMsgId)) {
            logger.info("forumMsgId");
            throw new AppException("forumMsgId不能为空");
        }
        logger.info("forumMsgId:" + forumMsgId);
        try {

            /**
             * 删除所有点赞生成的帖子以及分享的帖子
             */
            forummessageMapper.deleteLikePointMsgsByUser(forumMsgId);
            forummessageMapper.deleteShareMsgsByUser(forumMsgId);

            /**
             * 用户的发帖数-1
             */
            Forummessage message = forummessageMapper.selectByPrimaryKey(forumMsgId);
            if (null == message) {
                logger.info("待删除的帖子为空");
                throw new AppException("待删除的帖子为空");
            }

            logger.info("用户发帖数-1");
            if (StringUtils.hasText(message.getUserId())) {
                userFeignClient.totalArticleChange(message.getUserId(), -1);
            }

            /**
             * 如果为群组帖子，则将群组发帖数减1
             */
            if (ForumServciceStatic.groupMsg.equals(message.getMsgSourceType())) {
                if (StringUtils.hasText(message.getSourceId())) {
                    Forumgroup group = forumgroupMapper.selectByPrimaryKey(message.getSourceId());
                    if (null != group) {
                        group.setGroupMessageTotal(group.getGroupMessageTotal() - 1);
                        forumgroupMapper.updateByPrimaryKey(group);
                        logger.info("更新群组发帖数成功");
                    }
                }
            }

            //删除点赞记录和评论记录
            forumlikespointrecordService.deleleLikesPointRecordByMsgId(forumMsgId);
            forumcommentService.deleteCommentsByMsgId(forumMsgId);

            /**
             * 删除帖子
             */
            return forummessageMapper.deleteByPrimaryKey(forumMsgId);

        } catch (Exception e) {
            logger.info("删除猿圈帖子失败" + e);
            return 0;
        }
    }

    /**
     * 根据帖子id获取帖子详情，包括点赞数，点赞人，评论以及评论的评论
     *
     * @param forumMsgId
     * @return Forummessage
     * @author lid
     * @date 2017.6.22
     */
    @Transactional
    public Forummessage getForumMsgDetail(String forumMsgId, String userId) {
        if (!StringUtils.hasText(forumMsgId)) {
            logger.info("forumMsgId参数为空！");
            throw new AppException("forumMsgId参数为空！");
        }
        logger.info("getForumMsgDetail!forumMsgId=" + forumMsgId);

        Forummessage message = new Forummessage();

        try {
            message = forummessageMapper.selectMessagesDetail(forumMsgId);
            if (null == message) {
                logger.info("message为空！");
                throw new AppException("当前帖子已删除！");
            }
            /**
             * 获取分享的内容
             */
            this.getShareContent(message, userId);

            /**
             * 判断我是否点赞,因为存在分享的帖子，所以分享出去的帖子是没有userId的
             */
            if (StringUtils.hasText(userId)) {
                int count = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, message.getForumMsgId());
                if (0 < count) {
                    message.setHasPraised(1);
                }
            }

            logger.info("获取点赞信息!");
            //获取点赞信息
            List<Forumlikespointrecord> listForumlikespointrecord = forumlikespointrecordService.getLikesRecordByMsgId(forumMsgId);
            if (((null == listForumlikespointrecord) || (0 == listForumlikespointrecord.size()))
                    && (0 != message.getLikesCount())) {
                logger.info("当前帖子点赞数据为0，修改当前帖子的点赞数为0！");
                forummessageMapper.updateLikesCount(forumMsgId, 0);
                message.setLikesCount(0);
            }

            logger.info("更新点赞信息!");
            //如果帖子中的点赞数跟搜索到的点赞记录不符  则更新点赞数
            if (message.getLikesCount() != listForumlikespointrecord.size()) {
                logger.info("帖子中的点赞数跟搜索到的点赞记录不符,更新点赞数!message.getLikesCount():" + message.getLikesCount()
                        + ",listForumlikespointrecord.size():" + listForumlikespointrecord.size());

                forummessageMapper.updateLikesCount(forumMsgId, listForumlikespointrecord.size());
                message.setLikesCount(listForumlikespointrecord.size());
            }

            logger.info("获取评价信息!");

            message.setListForumlikespointrecord(listForumlikespointrecord);

            logger.info("获取媒体资源信息!");
            //获取媒体资源信息
            List<Forummediaresource> listForummediaresource =
                    forummediaresourceMapper.getMediaResourceByMsgId(message.getForumMsgId());
            message.setListForummediaresource(listForummediaresource);

            //判断是否关注
            if (StringUtils.hasText(userId)) {
                Integer isAttention = forumuserattentionanotherrelService.isAttention(userId, message.getUserId());
                if ((null != isAttention)
                        && (1 == isAttention)) {
                    message.setIsAttentioned("yes");
                }
            }
        } catch (Exception e) {
            logger.info("根据帖子id获取帖子详情异常！");
            return null;
        }
        return message;
    }

    /**
     * 获取首页推荐的3D视频和酷视频
     * 1，获取最新的用户未浏览过的推荐3D视频和酷视频各10条
     * 2，如果获取的为空，则直接获取最新的推荐3D视频和酷视频
     * 3，每次获取到的推荐3D视频和酷视频存入用户的浏览记录中
     *
     * @param msgType
     * @return
     */
    @Transactional
    public List<Forummessage> getIndexRecommandMsgs(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId为空！");
        }

        try {
            List<Forummessage> listResult = new ArrayList<Forummessage>();

            //获取最新的10条推荐3D视频
            List<Forummessage> listThreeDimensionalVideo = forummessageMapper.
                    getIndexRecommandMsgs(ForumServciceStatic.threeDimensionalVideo, userId);

            logger.info("listThreeDimensionalVideo.size():" + listThreeDimensionalVideo.size());

            if ((null == listThreeDimensionalVideo)
                    || (0 == listThreeDimensionalVideo.size())) {
                //获取最新的1条推荐3D视频
                listThreeDimensionalVideo = forummessageMapper.getOneRecommandMsg(ForumServciceStatic.threeDimensionalVideo);
                listResult.add(listThreeDimensionalVideo.get(0));
            } else {
                //随机获取一条
                Collections.shuffle(listThreeDimensionalVideo);
                listResult.add(listThreeDimensionalVideo.get(0));
                //存入用户浏览记录中
                msgViewRecordService.saveRecord(listThreeDimensionalVideo.get(0).getForumMsgId(),
                        userId, ForumServciceStatic.threeDimensionalVideo);
            }

            List<Forummessage> listShortVideo = forummessageMapper.
                    getIndexRecommandMsgs(ForumServciceStatic.shortVideo, userId);

            logger.info("listShortVideo.size():" + listShortVideo.size());

            if ((null == listShortVideo)
                    || (0 == listShortVideo.size())) {
                //获取最新的1条推荐酷视频
                listShortVideo = forummessageMapper.getOneRecommandMsg(ForumServciceStatic.shortVideo);
                listResult.add(listShortVideo.get(0));
            } else {
                //随机获取一条
                Collections.shuffle(listShortVideo);
                listResult.add(listShortVideo.get(0));
                msgViewRecordService.saveRecord(listShortVideo.get(0).getForumMsgId(),
                        userId, ForumServciceStatic.shortVideo);
            }

            return listResult;
        } catch (Exception e) {
            throw new AppException("获取首页推荐视频失败!");
        }
    }


    /**
     * 分页获取推荐的帖子
     *
     * @param msgType
     * @return
     */
    @Transactional
    public List<Forummessage> getRecommandMsgByType(String userId, String currentMsgId, String msgType, Integer currentPage, Integer rows) {
        try {
            if (!StringUtils.hasText(msgType)) {
                throw new AppException("帖子类型参数为空！");
            }

            //首先获取未看过的推荐视频，然后获取已看过的视频
            List<Forummessage> listForummessage = forummessageMapper.getRecommandMsgByType(msgType, userId);
            List<String> msgViewRecords = msgViewRecordService.getRecordsByUserId(userId);

            //已看过的推荐视频
            List<Forummessage> listViewedMsgs = new ArrayList<>();
            //未看过的推荐视频
            List<Forummessage> listNotViewedMsgs = new ArrayList<>();

            for (Forummessage msg : listForummessage) {
                if (msgViewRecords.contains(msg.getForumMsgId())) {
                    listViewedMsgs.add(msg);
                    continue;
                }

                listNotViewedMsgs.add(msg);
            }

            listNotViewedMsgs.addAll(listViewedMsgs);

            List<String> listLikePointRecords = forumlikespointrecordService.getLikePointMsgsByUserId(userId);
            List<String> listAttentUserIds = forumuserattentionanotherrelService.getMyAttentionUsers(userId);
            //判断当前帖子的用户是否被关注以及当前帖子我是否已经点赞
            Iterator<Forummessage> iterator = listNotViewedMsgs.iterator();
            while (iterator.hasNext()) {
                Forummessage forummessage = iterator.next();
                if ((StringUtils.hasText(currentMsgId))
                        && (currentMsgId.equals(forummessage.getForumMsgId()))) {
                    iterator.remove();
                    continue;
                }

                if (listLikePointRecords.contains(forummessage.getForumMsgId())) {
                    forummessage.setHasPraised(1);
                }

                if (listAttentUserIds.contains(forummessage.getUserId())) {
                    forummessage.setIsAttentioned("yes");
                }

            }

            /**
             * 手动分页
             */
            logger.info("listForummessage.size():" + listNotViewedMsgs.size());

            Integer length = listNotViewedMsgs.size();

            Integer startIndex = rows * (currentPage);
            Integer endIndex = rows * (currentPage + 1);
            if (startIndex > length) {
                return null;
            }

            if (endIndex < length) {
                List<Forummessage> listResult = listNotViewedMsgs.subList(startIndex, endIndex);
                return listResult;
            }
            List<Forummessage> listResult = listNotViewedMsgs.subList(startIndex, length);
            return listResult;
        } catch (Exception e) {
            logger.info("分页获取推荐的帖子!" + e);
            return null;
        }
    }

    /**
     * 分页查找
     *
     * @param rows
     * @param currentPage
     * @return List<Forummessage>
     * @author lid
     * @date 2017.6.6
     */
    @Transactional
    public PageData getAllForummessageByPage(QueryMsgsVo vo) {
        try {
            if (null == vo.getOffset()
                    || null == vo.getLimit()) {
                throw new AppException("分页参数为空！");
            }

            PageData page = new PageData();

            if (StringUtils.hasText(vo.getPhoneNo())) {
                User user = userFeignClient.findByPhoneNo(vo.getPhoneNo()).getData();
                if (null != user) {
                    vo.setUserId(user.getUserId());
                } else {
                    List<Forummessage> listForummessage = new ArrayList<Forummessage>();
                    page.setRows(listForummessage);
                    page.setTotal(0);
                    return page;
                }
            }
            List<Forummessage> listForummessage = forummessageMapper.getAllForummessageByPage(vo);
            /**
             * 手动分页
             */
            logger.info("size:" + listForummessage.size());
            Integer length = listForummessage.size();
            page.setTotal(length);

            Integer startIndex = vo.getLimit() * (vo.getOffset() - 1);
            Integer endIndex = vo.getLimit() * vo.getOffset();
            if (startIndex > length) {
                return null;
            }

            if (endIndex < length) {
                List<Forummessage> listResult = listForummessage.subList(startIndex, endIndex);
                page.setRows(listResult);
                return page;
            }
            List<Forummessage> listResult = listForummessage.subList(startIndex, length);
            page.setRows(listResult);
            return page;
        } catch (Exception e) {
            logger.info("分页获取猿圈帖子失败" + e);
            return null;
        }

    }

    /**
     * 获取所有的帖子总数
     *
     * @return int
     * @author lid
     * @date 2017.6.7
     */
    public int countAllMsgs() {
        return forummessageMapper.countAllMsgs();
    }

    /**
     * 根据关键字，贴子类型，创建时间查找帖子记录并分页
     *
     * @author lixs
     * @date 2017.6.9
     */
    @Transactional
    public List<Forummessage> getForumMsgByPage(String msgType, String msgContent, String createDateS, String createDateE, Integer rows, Integer currentPage) {
        try {
            PageHelper.startPage(currentPage, rows);
            List<Forummessage> listForummessage = forummessageMapper.getForumMsg(msgType, msgContent, createDateS, createDateE);
            return listForummessage;
        } catch (Exception e) {
            logger.info("获取帖子失败" + e);
            return null;
        }

    }

    /**
     * 根据关键字，贴子类型，创建时间查找帖子记录，用于记录查询记录的总条数
     *
     * @param msgType
     * @param msgContent
     * @param createDateS
     * @param createDateE
     * @return
     */
    @Transactional
    public List<Forummessage> getForumMsg(String msgType, String msgContent, String createDateS, String createDateE) {
        try {
            List<Forummessage> listForummessage = forummessageMapper.getForumMsg(msgType, msgContent, createDateS, createDateE);
            if (listForummessage == null) {
                throw new AppException("未找到相关帖子");
            }
            return listForummessage;
        } catch (Exception e) {
            logger.info("获取帖子失败" + e);
            return null;
        }

    }

    /**
     * 通过标签id list查找对应的帖子
     *
     * @param listMsgLabelIds
     * @return List
     * @author lid
     * @date 2017.6.8
     */
    public List<Forummessage> findMsgsByLabels(List<String> listMsgLabelIds) {
        if (1 == listMsgLabelIds.size()) {
            List<Forummessage> listForummessage = forummessageMapper.getMsgsBylabelId(listMsgLabelIds.get(0));
            return listForummessage;
        }

        if (2 == listMsgLabelIds.size()) {
            List<Forummessage> listForummessage = forummessageMapper.getMsgsByTwolabelIds(listMsgLabelIds.get(0), listMsgLabelIds.get(1));
            return listForummessage;
        }

        if (3 == listMsgLabelIds.size()) {
            List<Forummessage> listForummessage = forummessageMapper.getMsgsByThreelabelIds(listMsgLabelIds.get(0), listMsgLabelIds.get(1), listMsgLabelIds.get(2));
            return listForummessage;
        }
        return null;
    }

    /**
     * @param rows
     * @param currentPage
     * @param reportCount
     * @return List
     * @author lixs
     * @date 2017 6.9
     */
    public List<ForumReportVo> queryAllReportForumMsg(String forumHandle, int rows, int currentPage) {


        List<ForumReportVo> listForummessage = forummessageMapper.queryAllReportForumMsg(forumHandle);
        if (null == listForummessage) {
            throw new AppException("被举报帖子不能为空");
        }
        PageHelper.startPage(currentPage, rows);
        logger.info("被举报帖子数量" + listForummessage.size());
        return listForummessage;

    }

    /**
     * 查询被举报帖子数量
     *
     * @return int
     * @author lixs
     */
    public int countReportMsgs(String forumHandle) {
        return forummessageMapper.countReportMsgs(forumHandle);
    }


    /**
     * 根据帖子内容搜索帖子
     *
     * @param content
     * @return List<Forummessage>
     * @author lid
     * @date 2017.7.1
     */
    public List<Forummessage> searchMessageByContent(String userId, String content, Integer rows, Integer currentPage) {
        if (!StringUtils.hasText(content)) {
            throw new AppException("content参数为空！");
        }
        try {
            PageHelper.startPage(currentPage, rows);
            List<Forummessage> listForummessage = forummessageMapper.searchMessageByContent("%" + content + "%");
            for (Forummessage msg : listForummessage) {
                int myLikesCount = forumlikespointrecordMapper.countByUserIdAndForumMsgId(userId, msg.getForumMsgId());
                if (0 < myLikesCount) {
                    msg.setHasPraised(1);
                }
            }

            return listForummessage;
        } catch (Exception e) {
            logger.info("搜索帖子失败" + e);
            return null;
        }
    }

    /**
     * 统计我的帖子的点赞总数
     *
     * @param userId
     * @return int
     * @author lid
     * @date 2017.7.11
     */
    public int countLikePointsByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("userId参数为空！");
        }

        try {
            return forummessageMapper.countLikePointsByUserId(userId);
        } catch (Exception e) {
            logger.info("搜索帖子失败" + e);
            return -1;
        }
    }

    /**
     * 修改推荐状态
     *
     * @param forumMsgId
     * @param recommand
     * @return int
     * @author lid
     * @date 2017.10.12
     */
    public int updateRecommandStatus(String forumMsgId, Integer recommand) {
        if (!StringUtils.hasText(forumMsgId)) {
            throw new AppException("forumMsgId参数为空！");
        }

        if (null == recommand) {
            throw new AppException("recommand参数为空！");
        }

        try {
            return forummessageMapper.updateRecommandStatus(forumMsgId, recommand);
        } catch (Exception e) {
            logger.info("修改帖子推荐状态失败" + e);
            return -1;
        }
    }


    /**
     * 根据帖子的sourceType内容设置帖子的属性值
     *
     * @param message
     * @return Forummessage
     * @author lid
     * @date 2017.7.26
     */
    public Forummessage getSourceContent(Forummessage message, String userId) {
        switch (message.getMsgSourceType()) {
            case ForumServciceStatic.likePointMsg:
                logger.info("当前贴为点赞帖！msgId:" + message.getForumMsgId());
                Forummessage likePointMsg = this.getForumMsgDetail(message.getSourceId(), userId);
                logger.info("shareMsgContent:" + likePointMsg.getMsgContent());
                message.setShareForummessage(likePointMsg);
                break;
            case ForumServciceStatic.groupMsg:
                logger.info("当前贴为群组帖！msgId:" + message.getForumMsgId());
                Forumgroup group = forumgroupMapper.selectByPrimaryKey(message.getSourceId());
                if (null != group) {
                    message.setShareForumgroup(group);
                }
                break;

            default:
                break;
        }
        return message;
    }

    /**
     * 根据帖子的分享内容设置帖子的属性值
     *
     * @param message
     * @return Forummessage
     * @author lid
     * @date 2017.7.4
     */
    public Forummessage getShareContent(Forummessage message, String userId) {
        switch (message.getMsgType()) {
            case ForumServciceStatic.msg:
                break;

            case ForumServciceStatic.shareMsg:
                Forummessage shareForummessage = this.getForumMsgDetail(message.getSourceId(), userId);
                if (null != shareForummessage) {
                    message.setShareForummessage(shareForummessage);
                }
                break;

            case ForumServciceStatic.shareGroup:
                Forumgroup group = forumgroupMapper.selectByPrimaryKey(message.getSourceId());
                if (null != group) {
                    message.setShareForumgroup(group);
                }
                break;

            case ForumServciceStatic.shareNews:
                Long sourceId = Long.parseLong(message.getSourceId());
                ResultMessage<CmfPostsListVo> resultMessage = newsClient.getPostsListById(sourceId);
                CmfPostsListVo vo = resultMessage.getData();
                if (null != vo) {
                    logger.info("title:" + vo.getPostTitle());
                    message.setCmfPostsListVo(vo);
                }
                break;

            //TODO  其他类型的均在此处理
        }
        return message;
    }

    /**
     * 获取今天的帖子总数
     *
     * @return
     */
    public Integer countTodayNewMsgs() {
        Calendar cal = Calendar.getInstance();
        Date deadTime = new Date();
        cal.setTime(deadTime);

        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        deadTime = cal.getTime();
        Integer todayMsgs = forummessageMapper.countTodayNewMsgs(deadTime);
        logger.info("todayMsgs:" + todayMsgs);
        return todayMsgs;
    }

}
